<!--
 * @Author: adolphus adolphus520@163.com
 * @Date: 2022-12-10 00:18:29
 * @LastEditors: 姚杰鸿
 * @LastEditTime: 2024-11-07 14:28:17
 * @Description: file content
-->
<template>
  <div ref="switchRef">
    <el-switch
      v-model="isDarkTag"
      inline-prompt
      :active-icon="ElmMoonIcon"
      :inactive-icon="ElmSunnyIcon"
      active-color="var(--el-fill-color-dark)"
      inactive-color="var(--el-color-primary)"
      @change="toggleTheme"
    />
  </div>
</template>

<script lang="ts" setup>
import { useToggle } from "@vueuse/shared";
import { useDark } from "@vueuse/core";
import ElmMoonIcon from "@/components/elm/ElmMoonIcon.vue";
import ElmSunnyIcon from "@/components/elm/ElmSunnyIcon.vue";
import { ref } from "vue";

const isDark = useDark(),
  isDarkTag = ref(isDark.value),
  toggleDark = useToggle(isDark),
  switchRef = ref<HTMLElement>(),
  toggleTheme = () => {
    const { offsetLeft: x, offsetHeight: y } = switchRef.value as any;
    let dx = x + 10;
    let dy = y - 7;
    const endRadius = Math.hypot(
      Math.max(dx, innerWidth - dx),
      Math.max(dy, innerHeight - dy)
    );

    // 兼容性处理
    if (!document.startViewTransition) {
      toggleDark();
      return;
    }
    const transition = document.startViewTransition(async () => {
      toggleDark();
    });

    transition.ready.then(() => {
      const clipPath = [
        `circle(0px at ${dx}px ${dy}px)`,
        `circle(${endRadius}px at ${dx}px ${dy}px)`,
      ];
      console.log(isDarkTag.value);
      console.log(isDark.value);
      console.log([...clipPath].reverse());
      document.documentElement.animate(
        {
          clipPath: isDarkTag.value ? [...clipPath].reverse() : clipPath,
        },
        {
          duration: 500,
          easing: "ease-in-out",
          pseudoElement: isDarkTag.value
            ? "::view-transition-old(root)"
            : "::view-transition-new(root)",
        }
      );
    });
  };
</script>

<style lang="scss">
::view-transition-old(root),
::view-transition-new(root) {
  animation: none;
  mix-blend-mode: normal;
}

/* 进入dark模式和退出dark模式时，两个图像的位置顺序正好相反 */

::view-transition-old(root) {
  z-index: 1;
}

::view-transition-new(root) {
  z-index: 2147483646;
}

/* 根据自己选择器修改 */
[class="dark"]::view-transition-old(root) {
  z-index: 2147483646;
}
[class="dark"]::view-transition-new(root) {
  z-index: 1;
}
</style>
